# common/utils/middleware.py
from flask import request, current_app, g, jsonify
from api.jwt_api import verify_jwt
from exts import redis_store


def get_userinfo():
    # 1.获取请求头中的token信息 [登录token，刷新token]
    # 规定：前端通过Authorization字段携带token
    token = request.headers.get("Authorization")
    # 获取秘钥
    key = current_app.config["JWT_SECRET"]
    # 2.进行token校验
    # 载荷信息有可能为空：token为空，token错误，token过期
    payload = verify_jwt(token, key)
    # 默认值
    g.user_id = None
    g.is_refresh = False
    if payload:
        # 从redis中检验token是否存在
        if redis_store.get(f'test:user:token:{payload.get("user_id")}') is None or bytes.decode(
                redis_store.get(f'test:user:token:{payload.get("user_id")}')) != token:
            return jsonify({'to': '/login', 'message': 'token令牌验证失败', 'code': 2002})
        # 3.从载荷字典中提取用户身份信息
        g.user_id = payload.get("user_id")
        g.is_refresh = payload.get("is_refresh", False)
